import { useRef, useState } from "react";
import styles from "./index.module.less";
import {
	ProForm,
	ProFormInstance,
	ProFormText,
	ProFormRadio,
	ProFormSelect,
} from "@ant-design/pro-components";
import { Affix, Button, ConfigProvider, Flex, Space, message, Row, Col } from "antd";
import useUrl from "@/hooks/useUrl";
import { RESULT_CODES } from "@/api/helper/ResultCode";
import Loading from "@/components/Loading";
import { createTask, updateTask, getTaskDetail } from "@/api/modules/task";
import { getDictByCode, getTaskLevelDict } from "@/api/modules/dict";
import { getCarList } from '@/api/modules/device';
import { getAllJoint, getDockList } from "@/api/modules/platform";
import { getLineList, getSiteByScene, getLineDetail } from "@/api/modules/line";
import { useRequest } from "ahooks";
import { useEffect } from "react";
import AMap from "@/components/AMap";
import { CAR_TYPE_ENUM, ROUTE_TYPE_ENUM, SORT_LIST } from "./constant";
import { PlusOutlined, MinusOutlined } from '@ant-design/icons';
import { cloneDeep, map, omit, forEach } from 'lodash';
import { PageContainer } from '@ant-design/pro-layout';

type Site = {
  id: number;
};

export default () => {
	const formRef = useRef<ProFormInstance>();
	const { navigate, query } = useUrl();
	const detailId = query.get("detailId");
	const [routeType, setRouteType] = useState(ROUTE_TYPE_ENUM.loop);
	const [vehType, setVehType] = useState(CAR_TYPE_ENUM.assign);
  	const [selectFields, setSelectFields] = useState<Site[]>([]);
	const [siteList, setSiteList] = useState([]);
	const [loopPath, setLoopPath] = useState<any>([]); //环线线段列表
	const [loopMarker, setLoopMarker] = useState<any[]>([]); //环线点位列表
	const [allSites, setAllSites] = useState<any>({});
	const [allDockList, setAllDockList] = useState<any[]>([]);
	const [lineDetail, setLineDetail] = useState<any>(null); // 环线详情
	const [linePolygons, setLinePolygons] = useState<any[]>([]); // 环线场景范围
	const [linePolylinePaths, setLinePolylinePaths] = useState<any[]>([]); // 环线路径

	const { loading: loadingDetail, runAsync: getDetailAsync, data: walkDetailInfo } = useRequest(getTaskDetail, { manual: true });

	useEffect(() => {
		handleGetAllJoint();
		handleGetDockList();
		if (!detailId) return;
		getDetailAsync({ id: detailId }).then(async (res: any) => {
			if (res?.code === RESULT_CODES.SUCCESS) {
				const data = res?.data ?? {};
				const dataSiteList = cloneDeep(data?.siteList);
				setSelectFields(dataSiteList.slice(1, -1));
				
				const path = map(data?.siteList, (item: any) => {
					return item.lonLat?.split(',')
				})
				console.log(data?.siteList, "<============path")
				setLoopPath([{path}])
				setLoopMarker(map(data?.siteList, (item: any) => {
					const position = item.lonLat?.split(',')
					return { position: [position[0], position[1]] }
				}))
				setVehType(data.vehType);
          		setRouteType(data.rtType);
				const InitialData = {
					...data,
					startDock: data?.siteList?.[0]?.scId,
					endDock: data?.siteList?.[data?.siteList?.length - 1]?.scId,
					startSite: data?.siteList?.[0]?.id,
					endSite: data?.siteList?.[data?.siteList?.length - 1]?.id
				};
				// 先设置表单数据
				formRef.current?.setFieldsValue(InitialData);
				// 然后异步加载站点数据，确保 allSites 状态正确更新
				try {
					// 加载起始站和终点站的站点数据
					await handleDockChange(data?.siteList?.[0]?.scId, 'start');
					await handleDockChange(data?.siteList?.[data?.siteList?.length - 1]?.scId, 'end');
					// 处理途径点数据
					for (let index = 0; index < (dataSiteList || [])?.length; index++) {
						const item = dataSiteList[index];
						if(index !== 0 && index !== dataSiteList?.length - 1) {
							InitialData[`select${item.id}`] = item.id;
							InitialData[`dock${item.id}`] = item.scId;
							await handleDockChange(item.scId, item.id);
						}
					}
					// 重新设置表单数据，包含站点选择
					formRef.current?.setFieldsValue(InitialData);
				} catch (error) {
					console.error('处理站点数据失败:', error);
				}
			}
		});
	}, []);

	const handleValuesChange = (changeValue: any) => {
		if ('rtType' in changeValue) {
          setRouteType(changeValue.rtType);
          // 切换路线类型时清空环线数据
          if (changeValue.rtType !== ROUTE_TYPE_ENUM.loop) {
            setLineDetail(null);
            setLinePolygons([]);
            setLinePolylinePaths([]);
          }
        }
		if ('vehType' in changeValue) {
			if(changeValue.vehType === CAR_TYPE_ENUM.random) {
				formRef.current?.setFieldsValue({ level: 1 });
			}
          setVehType(changeValue.vehType);
        }
		
		// 监听业务环线变化
		if ('loopId' in changeValue) {
			handleGetLineDetail(changeValue.loopId);
		}
		
		// 监听站点变化，更新地图路径
		if ('startSite' in changeValue || 'endSite' in changeValue) {
			updateLoopPath();
		}
		
		// 监听途径点变化
		Object.keys(changeValue).forEach(key => {
			if (key.startsWith('select') && changeValue[key]) {
				updateLoopPath();
			}
		});
	};

	const handleSubmit = () => {
		const values = formRef.current?.getFieldsFormatValue?.();
		let objNameArr: any = []
		const siteIdArr = map(selectFields, (item: any) => {
			const id = `select${item.id}`
			objNameArr.push(id)
			return values[id]
		})
		const newValues = omit(values, ['startSite', 'endSite', 'startDock', 'endDock', ...objNameArr])
		const requestData = {
			...newValues,
			siteIds: [values.startSite, ...siteIdArr, values.endSite]
		};
		const callback = () => {
			if(detailId) {
				updateTask({ ...requestData, id: detailId }).then((res: any) => {
					if (res?.code === RESULT_CODES.SUCCESS) {
						message.success("保存成功");
						handleBack();
					}
				});
			} else {
				createTask({ ...requestData }).then((res: any) => {
					if (res?.code === RESULT_CODES.SUCCESS) {
						message.success("保存成功");
						handleBack();
					}
				});
			}
		};
		formRef.current?.validateFieldsReturnFormatValue?.().then(() => {
			callback();
		});
	};

	const handleBack = () => {
		navigate("/task/list");
	};

	//获取接字典类型
	const handleGetDict = async (code: any) => {
		const res: any = await getDictByCode({ parentId: 0, code })
		if (res?.code === RESULT_CODES.SUCCESS) {
			return res?.data
		}
	}

	//获取任务优先级列表 
	const handleGetTaskLevel = async () => {
		const res: any = await getTaskLevelDict({ parentId: 0, code: 'JOB_STATUS' })
		if (res?.code === RESULT_CODES.SUCCESS) {
			return res?.data
		}
	}
	

	//获取全量站点列表 
	const handleGetAllJoint = async () => {
		getAllJoint({ page: { pageNum: 1, pageSize: 100 } }).then((res: any) => {
			if (res?.code === RESULT_CODES.SUCCESS) {
				setSiteList(res?.data?.list)
			}
		})
	}

	//获取全量月台列表
	const handleGetDockList = async () => {
		const res: any = await getDockList({ page: { pageNum: 1, pageSize: 100 } })
		if (res?.code === RESULT_CODES.SUCCESS) {
			setAllDockList(res?.data?.list); 
		}
	}

	//获取环线列表
	const handleGetLineList = async () => {
		const res: any = await getLineList({ page: { pageNum: 1, pageSize: 100 } })
		if (res?.code === RESULT_CODES.SUCCESS) {
			return res?.data?.list
		}
	}

	//获取环线详情
	const handleGetLineDetail = async (lineId: string) => {
		if (!lineId) {
			setLineDetail(null);
			setLinePolygons([]);
			setLinePolylinePaths([]);
			return;
		}
		
		try {
			const res: any = await getLineDetail({ id: lineId });
			if (res?.code === RESULT_CODES.SUCCESS) {
				const data = res?.data ?? {};
				setLineDetail(data);
				
				// 处理场景范围数据 (polygons)
				const polygons = map(data?.sceneList || [], (scene: any) => {
					try {
						const points = JSON.parse(scene?.points || '[]');
						return {
							path: points,
							strokeColor: scene?.color || "#01B2A8",
							fillColor: scene?.color || "#01B2A8",
							strokeWeight: 2
						};
					} catch (error) {
						console.error('解析场景范围数据失败:', error);
						return null;
					}
				}).filter(Boolean);
				setLinePolygons(polygons);
				
				// 处理环线路径数据 (polylinePaths)
				const path = map(data?.siteList || [], (item: any) => {
					const position = item.lonLat?.split(',');
					return [position[0], position[1]];
				});
				
				if (path?.length > 0) {
					setLinePolylinePaths([{
						path,
						strokeColor: "#00847C",
						strokeWeight: 10,
						strokeStyle: "solid",
						showDir: true
					}]);
					
					// 更新环线标记点
					setLoopMarker(path.map((position: any) => ({
						position: [position[0], position[1]]
					})));
				} else {
					setLinePolylinePaths([]);
					setLoopMarker([]);
				}
			}
		} catch (error) {
			console.error('获取环线详情失败:', error);
			setLineDetail(null);
			setLinePolygons([]);
			setLinePolylinePaths([]);
		}
	};

	//获取车辆列表
	const handleGetCarList = async () => {
		const res: any = await getCarList({ page: { pageNum: 1, pageSize: 100 } })
		if (res?.code === RESULT_CODES.SUCCESS) {
			return res?.data?.list
		}
	}

	// 添加选择框
	const handleAdd = (index: any) => {
		let result: any = cloneDeep(selectFields)
		if(selectFields.length <= 0) {
			result.push({id: Date.now() })
		} else {
			result.splice(index, 0, { id: Date.now() })
		}
		setSelectFields(result);
		// 添加途径点后更新路径
		setTimeout(() => updateLoopPath(), 100);
	};

	// 删除选择框
	const handleRemove = (index: any) => {
		let result: any = cloneDeep(selectFields)
		result?.splice(index, 1)
		setSelectFields(result);
		// 删除途径点后更新路径
		setTimeout(() => updateLoopPath(), 100);
	};

	// 处理月台选择变化
	const handleDockChange = async (value: string, id: any) => {
		if (!value) {
			// 如果值为空，清空对应的站点列表
			setAllSites((prev: any) => {
				const updated = cloneDeep(prev);
				updated[id] = [];
				return updated;
			});
			updateLoopPath();
			return;
		}
		
		try {
			const sites = await getSiteByScene({id: value});
			// 确保数据结构正确，如果 sites?.data 是数组，直接使用；如果是对象，提取 list 字段
			const siteData = Array.isArray(sites?.data) ? sites.data : sites?.data?.list || [];
			
			// 使用函数式更新确保状态正确
			setAllSites((prev: any) => {
				const updated = cloneDeep(prev);
				updated[id] = siteData;
				return updated;
			});
		} catch (error) {
			console.error('获取站点列表失败:', error);
			// 如果请求失败，清空对应的站点列表
			setAllSites((prev: any) => {
				const updated = cloneDeep(prev);
				updated[id] = [];
				return updated;
			});
		}
	};

	// 更新环线路径
	const updateLoopPath = () => {
		const values = formRef.current?.getFieldsFormatValue?.();
		if (!values) return;

		const path: any[] = [];
		
		// 添加起始站
		if (values.startSite) {
			// 先从 allSites.start 中查找，如果没找到再从 siteList 中查找
			let startSite = allSites?.start?.find((site: any) => site.id === values.startSite);
			if (!startSite) {
				startSite = siteList.find((site: any) => site.id === values.startSite);
			}
			if (startSite?.lonLat) {
				const position = startSite.lonLat.split(",");
				path.push([position[0], position[1]]);
			}
		}
		
		// 添加途径点
		selectFields.forEach((field: any) => {
			const siteId = values[`select${field.id}`];
			if (siteId) {
				// 先从 allSites[field.id] 中查找，如果没找到再从 siteList 中查找
				let site = allSites?.[field.id]?.find((s: any) => s.id === siteId);
				if (!site) {
					site = siteList.find((s: any) => s.id === siteId);
				}
				if (site?.lonLat) {
					const position = site.lonLat.split(',');
					path.push([position[0], position[1]]);
				}
			}
		});
		
		// 添加终点站
		if (values.endSite) {
			// 先从 allSites.end 中查找，如果没找到再从 siteList 中查找
			let endSite = allSites?.end?.find((site: any) => site.id === values.endSite);
			if (!endSite) {
				endSite = siteList.find((site: any) => site.id === values.endSite);
			}
			if (endSite?.lonLat) {
				const position = endSite.lonLat.split(',');
				path.push([position[0], position[1]]);
			}
		}
		
		// 更新路径和标记点
		if (path.length > 0) {
			setLoopPath([{ path }]);
			setLoopMarker(path.map((position: any) => ({
				position: [position[0], position[1]]
			})));
		} else {
			setLoopPath([]);
			setLoopMarker([]);
		}
	};

	return (
		<PageContainer
			title=" "
			breadcrumb={{
				routes: [
					{ href: '/task/list', breadcrumbName: '任务管理' },
					{ href: '', breadcrumbName: detailId ? '编辑任务' : '新增任务' },
				],
			}}
		>
			<Loading isHeight100 loading={loadingDetail}>
				<div className={styles.detailContainer}>
					<div className={styles.container}>
						<ProForm
							colon={false}
							submitter={false}
							formRef={formRef}
							layout="horizontal"
							onValuesChange={handleValuesChange}
							labelCol={{ span: 6 }}
						>
							<div className={styles.content_wrap}>
								<div className={styles.content}>
									<div className={styles.moduleTitle}>{detailId ? "修改任务" : "新增任务"}</div>
									<ProFormText
										label="任务名称"
										name="jobName"
										rules={[
											{ required: true, message: "请输入任务名称" },
										]}
									/>
									<ProFormSelect
										label="任务类型"
										name="jobType"
										rules={[{ required: true, message: "请选择任务类型" }]}
										placeholder={"请选择任务类型"}
										request={() => handleGetDict('JOB_TYPE')}
									/>
									<ProFormRadio.Group
										label="路线类型"
										name="rtType"
										rules={[{ required: true, message: "请选择路线类型" }]}
										// options={ROUTE_TYPE_LIST}
										request={() => handleGetDict('JOB_ROUTE')}
										initialValue={ROUTE_TYPE_ENUM.loop}
									/>
									{
										routeType === ROUTE_TYPE_ENUM.diy &&
										<div style={{width: '100%'}}>
											<Row className={styles.mapFieldsItem}>
												<Col span={14} className={styles.pr10}>
													<ProFormSelect
														label="起始站"
														labelCol={{ span: 10 }}  // 设置label占用的栅格列数
														name="startDock"
														rules={[{ required: true, message: "关联月台" }]}
														placeholder={"关联月台"}
														options={allDockList}
														fieldProps={{
															fieldNames: {
																label: 'scName',  // 显示文本对应的字段
																value: 'id',    // 值对应的字段
															},
															onChange: (value: any) => handleDockChange(value, 'start')
														}}
													/>
												</Col>
												<Col span={7}>
													<ProFormSelect
														name={`startSite`}
														// labelCol={{ span: 7 }}  // 设置label占用的栅格列数
														// label={'起始站'}
														options={allSites?.start}
														fieldProps={{
															fieldNames: {
																label: 'name',  // 显示文本对应的字段
																value: 'id',    // 值对应的字段
															}
														}}
													/>
												</Col>
												<Col className={styles.itemBtnGroup} span={3}>
													<Button 
														icon={<PlusOutlined />} 
														onClick={() => handleAdd(0)}
													/>
												</Col>
											</Row>
											{
												selectFields.map((field, index) => (
													<div key={field.id} className={styles.mapFieldsItem}>
														<Col span={14} className={styles.pr10}>
															<ProFormSelect
																label="途径点"
																labelCol={{ span: 10 }}  // 设置label占用的栅格列数
																name={`dock${field.id}`}
																rules={[{ required: true, message: "关联月台" }]}
																placeholder={"关联月台"}
																options={allDockList}
																fieldProps={{
																	fieldNames: {
																		label: 'scName',  // 显示文本对应的字段
																		value: 'id',    // 值对应的字段
																	},
																	onChange: (value: any) => handleDockChange(value, field.id)
																}}
															/>
														</Col>
														<Col span={5}>
															<ProFormSelect
																key={field.id}
																name={`select${field.id}`}
																// labelCol={{ span: 7 }}  // 设置label占用的栅格列数
																// label={'途径点'}
																options={allSites?.[field.id]}
																fieldProps={{
																	fieldNames: {
																		label: 'name',  // 显示文本对应的字段
																		value: 'id',    // 值对应的字段
																	}
																}}
															/>
														</Col>
														<Col className={styles.itemBtnGroup} span={5}>
															<Button 
																icon={<MinusOutlined />} 
																onClick={() => handleRemove(index)}
																danger
															/>
															<Button 
																icon={<PlusOutlined />} 
																onClick={() => handleAdd(index + 1)}
															/>
														</Col>
													</div>
												))
											}
											<Row className={styles.mapFieldsItem}>
												<Col span={14} className={styles.pr10}>
													<ProFormSelect
														label="终点站"
														labelCol={{ span: 10 }}  // 设置label占用的栅格列数
														name="endDock"
														rules={[{ required: true, message: "关联月台" }]}
														placeholder={"关联月台"}
														options={allDockList}
														fieldProps={{
															fieldNames: {
																label: 'scName',  // 显示文本对应的字段
																value: 'id',    // 值对应的字段
															},
															onChange: (value: any) => handleDockChange(value, 'end')
														}}
													/>
												</Col>
												<Col span={10}>
													<ProFormSelect
														name={`endSite`}
														// labelCol={{ span: 7 }}  // 设置label占用的栅格列数
														// label={'终点站'}
														options={allSites?.end}
														fieldProps={{
															fieldNames: {
																label: 'name',  // 显示文本对应的字段
																value: 'id',    // 值对应的字段
															}
														}}
													/>
												</Col>
											</Row>
										</div>
									}
									{
										routeType === ROUTE_TYPE_ENUM.loop &&
										<ProFormSelect
											label="业务环线"
											name="loopId"
											rules={[{ required: true, message: "请选择业务环线" }]}
											placeholder={"请选择业务环线"}
											request={() => handleGetLineList()}
											fieldProps={{
												fieldNames: {
													label: 'loopName',  // 显示文本对应的字段
													value: 'id',    // 值对应的字段
												}
											}}
										/>
									}
									<ProFormRadio.Group
										label="车辆类型"
										name="vehType"
										rules={[{ required: true, message: "请选择车辆类型" }]}
										request={() => handleGetDict('JOB_VEHICLE')}
										fieldProps={{
											defaultValue: CAR_TYPE_ENUM.assign
										}}
										initialValue={CAR_TYPE_ENUM.assign}
									/>
									{
										vehType === CAR_TYPE_ENUM.assign &&										
										<ProFormSelect
											label="指定车辆"
											name="vehId"
											rules={[{ required: true, message: "请选择指定车辆" }]}
											placeholder={"请选择指定车辆"}
											request={() => handleGetCarList()}
											fieldProps={{
												fieldNames: {
													label: 'plateNo',  // 显示文本对应的字段
													value: 'id',    // 值对应的字段
												}
											}}
										/>
									}
									<ProFormSelect
										label="优先级"
										name="level"
										rules={[{ required: true, message: "请选择优先级" }]}
										placeholder={"请选择优先级"}
										options={SORT_LIST}
										fieldProps={{
											disabled: vehType === CAR_TYPE_ENUM.random,
										}}
										// request={() => handleGetTaskLevel()}
									/>
								</div>
							</div>
						</ProForm>
						<Flex justify="right" className={styles.btns}>
							<Space size={10}>
								<Button ghost type="primary" onClick={() => navigate(-1)}>
									返回
								</Button>
								<Button type="primary" onClick={handleSubmit}>
									保存
								</Button>
							</Space>
						</Flex>
					</div>
					<div className={styles.mapBox}>
						<div className={styles.moduleTitle}>地图预览</div>
						<div className={styles.mapOuter}>
							<AMap 
								polylinePaths={routeType === ROUTE_TYPE_ENUM.loop ? linePolylinePaths : loopPath} 
								markers={loopMarker}
								polygons={linePolygons}
							/>
						</div>
					</div>
				</div>
			</Loading>
		</PageContainer>
	);
};
